<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea :id="tinymceId" class="tinymce-textarea" />
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
// import editorImage from "./components/EditorImage";
import plugins from "./plugins";
import toolbar from "./toolbar";
import load from "./dynamicLoadScript";
import axios from "axios";
import service from "@/utils/request";
// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
const tinymceCDN =
  "https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js";

export default {
  name: "Tinymce",
  //   components: { editorImage },
  props: {
    id: {
      // 富文本编辑器的id
      type: String,
      default: function () {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      },
    },
    value: {
      type: String,
      default: "",
    },
    toolbar: {
      // 工具栏
      type: Array,
      required: false,
      default() {
        return [];
      },
    },
    menubar: {
      // 菜单栏
      type: String,
      default: "file edit insert view format table",
    },
    height: {
      // 富文本编辑器的高
      type: [Number, String],
      required: false,
      default: 360,
    },
    width: {
      // 富文本编辑器的宽
      type: [Number, String],
      required: false,
      default: "auto",
    },
    readonly: {
      // 富文本是否只读
      type: [Number, String],
      required: false,
      default: 0,
    },
  },
  data() {
    return {
      http: service.defaults.baseURL + "/upload",
      flag: true,
      hasChange: false, // 内容是否变化
      hasInit: false, // 初始化
      tinymceId: this.id, // 富文本id
      fullscreen: false, // 全屏
      readonlyOrno: "", // 是否为只读
    };
  },
  computed: {
    containerWidth() {
      const width = this.width;
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`;
      }
      return width;
    },
  },
  watch: {
    value(val) {
      //   console.log(val);
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => {
          //   console.log(tinymce);
          window.tinymce.get(this.tinymceId).setContent(val || "");
        });
      }
    },
    readonly(val, oldVal) {
      this.readonlyOrno = val;
    },
  },

  mounted() {
    this.readonlyOrno = this.readonly;
    this.init();
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce();
    }
  },
  deactivated() {
    this.destroyTinymce();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message);
          return;
        }
        this.initTinymce();
      });
    },
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        selector: `#${this.tinymceId}`, // 操作的对象
        language: "zh_CN", // 语言
        height: this.height,
        body_class: "panel-body ",
        readonly: this.readonlyOrno,
        object_resizing: false, // 是否允许编辑图片
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar, // 工具栏
        menubar: this.menubar, // 菜单栏
        plugins: plugins, // 插件
        end_container_on_empty_block: true, // 是否允许回车
        powerpaste_word_import: "clean",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square", // 默认的无序列表标记
        advlist_number_styles: "default", // 默认的有序列表标记
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"], // 图片跨域请求用的
        default_link_target: "_blank", // 链接的默认打开形式
        link_title: false,
        nonbreaking_force_tab: true, // 插入不间断空格需要不间断空格插件
        init_instance_callback: (editor) => {
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            this.$emit("input", editor.getContent());
          });
        },
        // setup(editor) {
        //   editor.on("FullscreenStateChanged", e => {
        //     _this.fullscreen = e.state;
        //   });
        // }
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        images_upload_handler(blobInfo, success, failure, progress) {
          uploadPic();
          let that = this;
          const token = "Bearer " + localStorage.getItem("token");
          // var formData = new FormData();
          // console.log(blobInfo.blob());
          // formData.append("file", blobInfo.blob());
          function uploadPic() {
            let formData = new FormData();
            // 服务端接收文件的参数名，文件数据，文件名
            formData.append("file", blobInfo.blob(), blobInfo.filename());
            axios
              .post(service.defaults.baseURL + "/upload", formData, {
                contentType: false,
                processData: false,
                headers: {
                  "Content-Type": "multipart/form-data",
                  Authorization: "Bearer " + localStorage.getItem("token"),
                },
              })
              .then((res) => {
                console.log(res);
                if (res.data.code == 0) {
                  success(
                    "https://mmkappnew.oss-cn-beijing.aliyuncs.com/" +
                      res.data.data
                  );
                }
              });
          }
          // getToken(token).then(response => {
          //   const url = response.data.qiniu_url;
          //   const formData = new FormData();
          //   formData.append('key', response.data.qiniu_key);
          //   formData.append('file', blobInfo.blob(), url);
          //   upload(formData).then(() => {
          //     success(url);
          //     progress(100);
          //   })
          // }).catch(err => {
          //   failure('出现未知问题，刷新页面，或者联系程序员')
          //   console.log(err);
          // });
        },
      });
    },
    // 销毁Tinymce
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      // if (this.fullscreen) {
      //   tinymce.execCommand("mceFullScreen");
      // }

      if (tinymce) {
        tinymce.destroy();
      }
    },
    // 新建内容
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    // 获取内容
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    // 在富文本编辑器中显示图片列表
    imageSuccessCBK(arr) {
      const _this = this;
      arr.forEach((v) => {
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(
            `<img style="width:100px;height:100px" class="wscnph" src="${v.url}" >`
          );
      });
    },
  },
};
</script>


